package com.ebs.md.container.esper;

/**
 * Revision Author:
 *  $File: //depot/MarketData/fxmonitor/main/src/main/java/com/ebs/md/container/esper/Jms2EsperAdapter.java $
 *  $Revision: #2 $
 *  $DateTime: 2012/08/29 08:53:06 $
 *  $Change: 114301 $
 *  $Author: Arik.Sher $
 */

import java.io.Serializable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageFormatException;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

/**
 * Adapter between JMS Messages(or Internal PubSub) to Esper (via IEsperAccessor)
 *
 */
public class Jms2EsperAdapter
implements MessageListener
{
    final protected Logger logger = Logger.getLogger(getClass());

    protected boolean        marketMonitorFeatureOn = true;
    protected IEsperAccessor esperAccessor;

	public void setEsperAccessor(IEsperAccessor esperAccessor) {
		this.esperAccessor = esperAccessor;
	}

	public void setMarketMonitorFeatureOn(boolean marketMonitorFeatureOn) {
		this.marketMonitorFeatureOn = marketMonitorFeatureOn;
	}

	public void init() {
		Assert.notNull(esperAccessor,  "'esperAccessor' is not set");
		
		if ( !marketMonitorFeatureOn ) {
			logger.info("Jms2EsperAdapter: MarketMonitor feature is turned OFF. will not send messages into Esper");
		} else {
			logger.info("Jms2EsperAdapter: MarketMonitor feature is turned ON.");
		}
	}
	
	/**
	 * assuming the message is ObjectMessage,
	 * and simply transferring it to the Esper Runtime.
	 */
	public void onMessage(Message jmsMessage) {
		if ( !marketMonitorFeatureOn ) {
			return;
		}
		if ( jmsMessage == null ) {
			logger.error("EsperAdapter: unexptected 001, jmsMessage is null");
			return;
		}
		Serializable obj = null;
		try {
			obj = extractObject(jmsMessage);
		} catch (JMSException e) {
			logger.error("EsperAdapter: unexptected 002, while extracting message", e);
		} catch (Throwable e) {
			logger.error("EsperAdapter: unexptected 007, while extracting message", e);
		}
		
		if ( obj != null ) {
			esperAccessor.getEPRuntime().sendEvent(obj);
		}
	}

	protected Serializable extractObject(Message jmsMessage) throws JMSException {
		if ( jmsMessage instanceof ObjectMessage ) {
			return ((ObjectMessage) jmsMessage).getObject();
		}
		throw new MessageFormatException("expecting jmsMessage to be 'ObjectMessage'. toString of it: " + jmsMessage );
	}
	
}
